package com.cjkj.framework.security.filter;

import com.alibaba.fastjson2.JSON;
import com.cjkj.common.constant.HttpStatus;
import com.cjkj.common.core.domain.AjaxResult;
import com.cjkj.common.core.domain.model.LoginUser;
import com.cjkj.common.core.redis.RedisCache;
import com.cjkj.common.utils.SecurityUtils;
import com.cjkj.common.utils.ServletUtils;
import com.cjkj.common.utils.StringUtils;
import com.cjkj.framework.web.service.TokenService;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * token过滤器 验证token有效性
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter
{
    @Resource
    private TokenService tokenService;

    @Resource
    private RedisCache redisCache;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException
    {
        LoginUser loginUser = tokenService.getLoginUser(request);
        if (StringUtils.isNotNull(loginUser) && StringUtils.isNull(SecurityUtils.getAuthentication()))
        {
            tokenService.verifyToken(loginUser);
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
            authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);

            // 重复请求
            String methodValue = request.getMethod();
            String url = request.getRequestURI();
            String token = loginUser.getToken();
            if(HttpMethod.POST.name().equals(methodValue) ||
                    HttpMethod.PUT.name().equals(methodValue) ||
                    HttpMethod.DELETE.name().equals(methodValue)){
                String key = "repeat-req:" + url +":"+ token;
                // 如果缓存中有这个url视为重复提交
                if ( redisCache.hasKey(key) ) {
                    redisCache.setCacheObject(key, "", 3, TimeUnit.SECONDS);
                    ServletUtils.renderString(response, JSON.toJSONString(AjaxResult.error(HttpStatus.NO_CONTENT, "请勿重复提交或者操作过于频繁！")));
                }
                redisCache.setCacheObject(key, "", 3, TimeUnit.SECONDS);
            }
        }

        chain.doFilter(request, response);
    }
}
